$(function () {
    $(document.body).click(function () {
        endEdit();
    });
});

function setProperty(id,name,value,propertyTargetId) {
    $('#'+id).data().property[name] = value;
    initProperty(name,value,propertyTargetId);
}

function setPropertys(id,data,propertyTargetId) {
    for( var n in data ){
        setProperty(id,n,data[n],propertyTargetId);
    }
}

function initProperty(name,value,propertyTargetId) {
    propertyTargetId = propertyTargetId ? propertyTargetId : '#property';
    var ele = $(propertyTargetId+' .gridtable tr div[name="'+name+'"]');
    var edit = ele.data().edit;
    if( edit == 'number' || edit == 'text' ){
        ele.find('.s1').html(value);
    }else if( edit == 'color' ){
        ele.find('.c10').css({"background":"#"+value});
    }else if( edit == 'none' ){
        ele.find('.s1').html(value);
    }else if( edit == 'font' ){
        ele.find('.s1').html(value[5]);
    }else if( edit =='select' ){
        ele.find('.s1').html(value.text);
    }else if( edit =='format' ){
        ele.find('.s1').html('');
        for(var i=0 ; i<formats.length ; i++){
            var oneFormat = formats[i];
            if( oneFormat.type == value ){
                ele.find('.s1').html(oneFormat.value);
            }

        }

    }
}

function getSelectedValue(name,edit) {
    var label = $('#printCenter label[select="1"]');
    var li = $('#sortable li[select="1"]');
    var value;
    if( label.length > 0 ){
        value = label.data().property[name];
    }else if(li.length > 0){
        value = li.data().property[name];
    }else{
        value = $('#printCenter').data().property[name];
    }
    if( edit == 'select' ){
        if( typeof(value) == 'object' ){
            value = value.value;
        }
    }
    return value;
}

function setSelectedValue(name,value) {
    var ele = $('#printCenter label[select="1"]');
    var unit = "px";
    if( ele.length ==0 ){
        ele = $('#sortable li[select="1"]');
    }
    if( ele.length == 0 ){
        /*
        （1）在水平方向上：
                             1mm=31.49606299px
                             1px=0.03175mm
        （2）在垂直方向上：
                             1mm=23.62204724px
                             1px=0.042333333mm
         */
        ele = $('#printCenter');
        unit = 'mm';
        //无选中则是布局属性
    }
    ele.data().property[name] = value;
    if( name=='x' ){
        ele.css({"left":value+"px"});
    }else if( name=='y' ){
        ele.css({"top":value+"px"});
    }else if( name=='width' ){
        ele.css({"width":value+unit});
    }else if( name=='height' ){
        ele.css({"height":value+unit});
    }else if(name=='index'){
        ele.css({"z-index":value});
    }else if(name=='align'){
        ele.css({"text-align":value.value});
    }else if(name=='font'){
        ele.css({"font-family": value[0],"font-weight": value[1],"font-style": value[2],"font-size": value[3]+"px","text-decoration":value[4]});
    }else if(name=='bg' || name=='headBg'){
        ele.css({"background":'#'+value});
    }else if(name=='color'){
        ele.css({"color":'#'+value});
    }else if(name == "paperType"){
        if( value.value =='A4' ){
            ele.css({"height":'297mm',width:'210mm'});
        }else if( value.value =='A42' ){
            ele.css({"height":'148.5mm',width:'210mm'});
        }
    }else if( name == 'txt_name' ){
        ele.find('span[type="text"]').html(value);
    }
}

function createPrintTable(row) {
    var table = $('<table class="gridtable"></table>');
    if(row.title){
        table.append('<caption>'+row.title+'</caption>');
    }
    for( var i=0 ; i<row.rows.length ; i++ ){
        var rowData = row.rows[i];
        var tr = $('<tr></tr>');
        tr.data(rowData);
        var td1 = $('<td style="width:120px;"><div class="cell" style="width:120px;"></div></td>');
        td1.find('.cell').append(rowData.label);

        var td2 = $('<td style="width:150px;"></td>');
        var td2Cell = $('<div class="cell" name="'+rowData.name+'" style="width:150px;padding-left: 0px;"></div>');
        //作为原始data 实际值与该data无关
        td2Cell.data(rowData);
        if( rowData.edit == 'color' ){
            var iconDiv = $('<div class="c10"></div>');
            iconDiv.css({"position":"absolute","top":"4px","left":"15px"});
            td2Cell.append(iconDiv);
        }else{
            td2Cell.html('<div class="s1">'+rowData.text+'</div>');
        }

        td2.append(td2Cell);

        td2.click(function (event) {
            /*var selectedEle = $('#printCenter label[select="1"]');
            if( selectedEle.length ==0 ){
                selectedEle = $('#sortable li[select="1"]');
            }
            if( selectedEle.length ==0 ){
                return ;
            }*/
            if(frameType == 'table'){
                if($('#sortable li[select="1"]').length ==0){
                    return;
                }
            }
            var data = $(this).parent().data();
            if( data.edit == 'number' || data.edit == 'text' ){
                createNumberEdit(this,data,event);
            }else if( data.edit == 'select' ){
                createSelectEdit(this,data,event);
            }else if( data.edit == 'font' ){
                createFontEdit(this,data,event);
            }else if( data.edit == 'color' ){
                createColorEdit(this,data,event);
            }else if(data.edit == 'format'){
                createFormatEdit(this,data,event);
            }else if(data.edit == 'table'){
                createTableEdit(this,data,event);
            }
        });

        tr.append(td1);tr.append(td2);
        table.append(tr);
    }
    return table;
}

function createFormatEdit(_this,data,event) {
    var cell = createEditBefore(_this,'input');
    if(!cell){
        return;
    }
    /*var cell = $(_this).find('.cell');
    if(cell.find('input').length > 0)return;
    endEdit(data);*/
    var input = $('<input edit="format" name="'+data.name+'" type="text"/>');
    input.width(110).height(26);
    input.val(cell.data().text);

    input.click(function (event) {
        event.stopPropagation();
    });

    var button = $('<button class="button"></button>');
    button.css({"position":"absolute","top":"2px","left":"99px","padding": "3px 3px 0px 5px"});
    var icon = $('<i class="fa fa-edit"></i>');
    icon.css({"font-size":"20px","color":"#ffffff"});
    icon.click(function (event) {
        top.rowData = data;
        app.window(parent.layer,{
            title:false,btn:[],maxmin:false,
            area: ['500px', '500px'],
            content: './print_format.html?name='+data.name
        });
        event.stopPropagation();
    });
    button.append(icon);
    button.click(function (event) {
        event.stopPropagation();
    });
    cell.empty().append(input).append(button);
    input.select();
    event.stopPropagation();
}

function createColorEdit(_this,data,event) {
    var cell = createEditBefore(_this,'input');
    if( cell ){
        var input = $('<input edit="color" name="'+data.name+'"/>');
        input.width(110).height(26);
        input.val('#'+getSelectedValue(data.name));

        var button = $('<button class="button"></button>');
        button.css({"position":"absolute","top":"2px","left":"99px","padding": "3px 3px 0px 3px"});
        var icon = $('<i class="fa fa-eraser"></i>');
        icon.css({"font-size":"20px","color":"#ffffff"});
        icon.click(function (event) {
            app.window(parent.layer,{
                title:false,btn:false,maxmin:false,
                area: ['320px', '270px'],
                content: './print_color.html?name='+data.name
            });
            event.stopPropagation();
        });
        button.append(icon);
        cell.empty().append(input).append(button);
        input.select();
        bindEditEvent([input,button],event);
    }

}

function createTableEdit(_this,data,event) {
    var cell = createEditBefore(_this,'input');
    if( cell ){
        var input = $('<input edit="font" readonly="readonly"/>');
        input.width(110).height(26);
        input.val('编辑表格各项属性');

        var button = $('<button class="button"></button>');
        button.css({"position":"absolute","top":"2px","left":"99px","padding": "3px 3px 0px 5px"});
        var icon = $('<i class="fa fa-edit"></i>');
        icon.css({"font-size":"20px","color":"#ffffff"});
        icon.click(function (event) {
            top.font = getSelectedValue(data.name);
            app.window(layer,{
                title:'表格',
                area: ['750px', '600px'],
                content: './print_table.html?name='+data.name
            });
            event.stopPropagation();
        });
        button.append(icon);
        cell.empty().append(input).append(button);
        bindEditEvent([input,button],event);
    }
}

function createFontEdit(_this,data,event) {
    var cell = createEditBefore(_this,'input');
    if( cell ){
        var input = $('<input edit="font"/>');
        input.width(110).height(26);
        input.val(getSelectedValue(data.name)[5]);

        var button = $('<button class="button"></button>');
        button.css({"position":"absolute","top":"2px","left":"99px","padding": "3px 3px 0px 5px"});
        var icon = $('<i class="fa fa-edit"></i>');
        icon.css({"font-size":"20px","color":"#ffffff"});
        icon.click(function (event) {
            top.font = getSelectedValue(data.name);
            app.window(parent.layer,{
                title:'字体',
                area: ['500px', '550px'],
                content: './print_font.html?name='+data.name
            });
            event.stopPropagation();
        });
        button.append(icon);
        cell.empty().append(input).append(button);
        bindEditEvent([input,button],event);
    }
}

function createNumberEdit(_this,data,event) {
    var cell = createEditBefore(_this,'input');
    if( cell ){
        var input = $('<input edit="'+data.edit+'" type="'+data.edit+'"/>');
        input.width($(_this).width()-2).height(26);
        input.val(getSelectedValue(data.name));
        cell.empty().append(input);
        input.select();
        bindEditEvent([input],event);
    }
}

function createSelectEdit(_this,data,event) {
    var cell = createEditBefore(_this,'select');
    if( cell ){
        var select = $('<select edit="select"></select>');
        select.width($(_this).width()-2).height(26);
        for( var i=0 ; i<data.values.length ; i++ ){
            var row = data.values[i];
            var option = $('<option value="'+row.value+'">'+row.name+'</option>');
            if( row.value == getSelectedValue(data.name,'select') ){
                option.attr("selected",true);
            }
            select.append(option);
        }
        $(_this).find('.cell').empty().append(select);
        bindEditEvent([select],event);
    }
}

function bindEditEvent(eles,parentEvent) {
    for( var i=0 ; i<eles.length ; i++ ){
        eles[i].click(function (event) {
            event.stopPropagation();
        });
    }
    eles[0].bind('keyup',function(event){
        if(event.keyCode ==13){
            endEdit();
        }
    });
    parentEvent.stopPropagation();
}

function createEditBefore(_this,type) {
    var cell = $(_this).find('.cell');
    if(cell.find(type).length > 0)return;
    endEdit();
    return cell;
}

function endEdit() {
    $('input[edit="number"],input[edit="text"]').each(endNumberEdit);
    $('select[edit="select"]').each(endSelectEdit);
    $('input[edit="font"]').each(endFontEdit);
    $('input[edit="format"]').each(endFontEdit);
    $('input[edit="color"]').each(endColorEdit);
}

function endNumberEdit() {
    var _this = $(this);
    var value = _this.val();
    var rowData = _this.parent().parent().parent().data();
    setSelectedValue(rowData.name,value);
    _this.parent().html('<div class="s1">'+value+'</div>');
}

function endSelectEdit() {
    var _this = $(this);
    var value = _this.val();
    var text = _this.find("option:selected").text();
    var rowData = _this.parent().parent().parent().data();
    setSelectedValue(rowData.name,{value:value,text:text});
    _this.parent().html('<div class="s1">'+text+'</div>');
}

function endFontEdit() {
    var _this = $(this);
    var value = _this.val();
    _this.parent().html('<div class="s1">'+value+'</div>');
}

function endColorEdit() {
    var _this = $(this);
    var value = _this.val();
    var rowData = _this.parent().parent().parent().data();
    setSelectedValue(rowData.name,value.replace('#',''));
    _this.parent().html('<div class="c10" style="position: absolute; top: 4px; left: 15px; background: '+value+';"></div>');
}